import React, { useState, useEffect, useCallback } from 'react';
import ReactFlow, { Handle, applyNodeChanges, useEdgesState, addEdge } from 'reactflow';
import axios from 'axios';
import 'reactflow/dist/style.css';

// 默认流程图数据
const defaultFlowData = {
  nodes: [
    {
      id: "1",
      type: "inputNode",
      position_x: 0,
      position_y: 0,
      data: {
        label: "输入节点",
        color: "#ffcccb",
        value: 10
      }
    },
    {
      id: "2",
      type: "ioNode",
      position_x: 200,
      position_y: 0,
      data: {
        label: "中间节点",
        color: "#90EE90",
        value: 2
      }
    },
    {
      id: "3",
      type: "outputNode",
      position_x: 400,
      position_y: 0,
      data: {
        label: "输出节点",
        color: "#87CEEB",
        result: 20
      }
    }
  ],
  edges: [
    {
      edge_id: "e1-2",
      source: "1",
      target: "2",
      source_handle: "right",
      target_handle: "left"
    },
    {
      edge_id: "e2-3",
      source: "2",
      target: "3",
      source_handle: "right",
      target_handle: "top"
    }
  ]
};

// 输入节点
const InputNode = ({ data, selected }) => {
  return (
    <div style={{ background: data.color, padding: 10, borderRadius: 5 }}>
      <div>{data.label}</div>
      <input
        type="number"
        value={data.value}
        onChange={data.onChange}
        style={{ width: 60, marginTop: 5 }}
      />
      <Handle type="source" position="right" id="right" />
    </div>
  );
};

// 输入输出节点
const InputOutputNode = ({ data, selected }) => {
  return (
    <div style={{ background: data.color, padding: 10, borderRadius: 5 }}>
      <div>{data.label}</div>
      <input
        type="number"
        value={data.value}
        onChange={data.onChange}
        style={{ width: 60, marginTop: 5 }}
      />
      <Handle type="target" position="left" id="left" />
      <Handle type="source" position="right" id="right" />
    </div>
  );
};

// 输出节点
const OutputNode = ({ data }) => {
  return (
    <div style={{ background: data.color, padding: 10, borderRadius: 5 }}>
      <div>{data.label}</div>
      <div style={{ fontSize: 24, marginTop: 5 }}>{data.result || '?'}</div>
      <Handle
        type="target"
        position="top"
        id="top"
        style={{ left: '50%', transform: 'translateX(-50%)' }}
      />
    </div>
  );
};

const nodeTypes = {
  outputNode: OutputNode,
  ioNode: InputOutputNode,
  inputNode: InputNode,
};

export default function App() {
  const [nodes, setNodes] = useState([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState([]);

  const onConnect = useCallback(
    (params) => setEdges((eds) => addEdge(params, eds)),
    [setEdges]
  );

  // 加载数据
  useEffect(() => {
    const fetchFlowData = async () => {
      try {
        const response = await axios.get('http://localhost:8000/api/flow-data/');
        let savedNodes = response.data.nodes;
        let savedEdges = response.data.edges;

        // 如果数据为空则使用默认数据
        if (savedNodes.length === 0 && savedEdges.length === 0) {
          savedNodes = defaultFlowData.nodes;
          savedEdges = defaultFlowData.edges;
        }

        const processedNodes = savedNodes.map(node => ({
          id: node.id,
          type: node.type,
          position: { x: node.position_x, y: node.position_y },
          data: {
            ...node.data,
            onChange: (e) => updateNodeValue(node.id, e.target.value),
          }
        }));

        setNodes(processedNodes);
        setEdges(savedEdges.map(edge => ({
          id: edge.edge_id,
          source: edge.source,
          target: edge.target,
          sourceHandle: edge.source_handle,
          targetHandle: edge.target_handle
        })));
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    };

    fetchFlowData();
  }, [setEdges, setNodes]);

  // 保存数据到后端
  const saveFlowData = useCallback(async () => {
    const nodeData = nodes.map(node => ({
      node_id: node.id,
      type: node.type,
      position_x: node.position.x,
      position_y: node.position.y,
      data: node.data
    }));

    const edgeData = edges.map(edge => ({
      edge_id: edge.id,
      source: edge.source,
      target: edge.target,
      source_handle: edge.sourceHandle,
      target_handle: edge.targetHandle
    }));

    try {
      await axios.post('http://localhost:8000/api/flow-data/', { 
        nodes: nodeData, 
        edges: edgeData 
      });
      alert('保存成功！');
    } catch (error) {
      console.error('保存失败:', error);
      alert('保存失败，请查看控制台');
    }
  }, [nodes, edges]);

  // 更新节点数值
  const updateNodeValue = (id, value) => {
    setNodes(ns => ns.map(node => 
      node.id === id ? { 
        ...node, 
        data: { ...node.data, value: Number(value) } 
      } : node
    ));
  };

  // 处理节点变化
  const onNodesChange = useCallback(
    (changes) => setNodes((nds) => applyNodeChanges(changes, nds)),
    []
  );

  return (
    <div style={{ height: '500px', position: 'relative' }}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        nodeTypes={nodeTypes}
        fitView
      />
      
      <button 
        onClick={saveFlowData}
        style={{
          position: 'absolute',
          top: 10,
          right: 10,
          zIndex: 5,
          padding: '8px 16px',
          background: '#4CAF50',
          color: 'white',
          border: 'none',
          borderRadius: 4,
          cursor: 'pointer'
        }}
      >
        保存数据
      </button>
    </div>
  );
}